//
//  YDPhotoShowAlbumViewController.swift
//  YDPhotoPicker
//
//  Created by alyadan on 16/7/31.
//  Copyright © 2016年 alyadan. All rights reserved.
//

import UIKit
import MVVM_BaseViewController
import YD_Util
import RxSwift
import RxCocoa
import SnapKit
import YD_ProgressHUD

class YDPhotoShowAlbumViewController: MVVM_BaseViewController {
    
    let greenColorValue = 0x11ce6e
    let lightGrayColorValue = 0xa9b7b7
    
    lazy var colloctionLayout = UICollectionViewFlowLayout()
    lazy var assetCollectionView:UICollectionView = UICollectionView(frame: CGRect(), collectionViewLayout: self.colloctionLayout)

    
    override var currentModel: YDPhotoShowAlbumVCModel{
       return vcModel.value as! YDPhotoShowAlbumVCModel
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.automaticallyAdjustsScrollViewInsets = false
        // Do any additional setup after loading the view.
//        setNavigationItemWithImageName("YDPhotoPicker.bundle/icon_back@3x.png", title: nil, location: BaseVCNavItemLocation_left)
    }
    
    
    lazy var sendBtn:UIButton = {
        let x = UIButton(type: UIButton.ButtonType.custom)
        x.setTitle("选择", for: .normal)
        x.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        x.setTitleColor(UIColor.init(HEXValue: self.greenColorValue) , for: .normal)
        x.setTitleColor(UIColor.init(HEXValue: self.lightGrayColorValue) , for: .disabled)
        x.isEnabled = false
        return x
    }()
    
    lazy var previewBtn:UIButton = {
        
        let x = UIButton(type: UIButton.ButtonType.custom)
        x.setTitle("预览", for: .normal)
//        x.titleEdgeInsets = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 0)
        x.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        x.setTitleColor(UIColor.init(HEXValue: 0x313131) , for: .normal)
        x.setTitleColor(UIColor.init(HEXValue: self.lightGrayColorValue) , for: .disabled)
        x.isEnabled = false
        return x
    }()
    
    lazy var selectCountLabel:UILabel = {
       let x = UILabel()
        x.backgroundColor = UIColor(HEXValue: self.greenColorValue)
        x.textAlignment = .center
        x.text = "12"
        x.textColor = UIColor.white
        x.layer.cornerRadius = 15
        x.layer.masksToBounds = true
        return x
    }()
    
    lazy var bottomControlView:UIView = {
        let x = UIView()
        x.addSubview(self.previewBtn)
        x.addSubview(self.sendBtn)
        x.addSubview(self.selectCountLabel)
        x.backgroundColor = UIColor(HEXValue: 0xf0f0f0, alpha: 1)
        return x
    }()
    
    override func setupUI() {
        currentModel.setupCollectionLayout(layout: colloctionLayout)
        assetCollectionView.backgroundColor = UIColor.white
        
        
        if let bundle = Bundle.getBundle(name: "YD_Photo_Picker_bundle"){
            assetCollectionView.register(UINib.init(nibName: "AssetCollectionViewCell", bundle: bundle), forCellWithReuseIdentifier: currentModel.assetColloctionID)
        }
        assetCollectionView.dataSource = currentModel
        assetCollectionView.delegate = currentModel
        view.addSubview(assetCollectionView)
        
        
        //MARK -- bottom tool bar
        //只有选图模式下才有toolBar
        view.addSubview(bottomControlView)
        
        
        //Navigation
        setNavgationItem(withImageName: nil, orTitle: "取消", location: .right)
        
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        
        hasScrollToBottom = true
    }
    
    
    
    
    override func addActionTarget() {
        previewBtn.rx.tap
            .subscribe(onNext: {[unowned self] in
                self.currentModel.preview()
            })
            .addDisposableTo(disposeBag)
        
        sendBtn.rx.tap
            .subscribe(onNext:{[unowned self] in
                               self.currentModel.sendAction()
            })
            .addDisposableTo(disposeBag)
        
    }
    
    override func bindModelData() {
        
        currentModel.selectedAssets.asObservable()
            .bindNext {[unowned self] (x:[PHAsset]) in
            self.selectCountLabel.isHidden = (x.count == 0)
            self.sendBtn.isEnabled = (x.count != 0)
            self.previewBtn.isEnabled = (x.count != 0)
            self.selectCountLabel.text = String(x.count)
        }
        .addDisposableTo(disposeBag)
    }
    
    var hasScrollToBottom = false
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        
        assetCollectionView.snp.makeConstraints {[unowned self] (ConstraintMaker) in
            ConstraintMaker.top.equalTo(self.topLayoutGuide.snp.bottom)
            ConstraintMaker.left.right.equalTo(self.view)
            ConstraintMaker.bottom.equalTo(self.bottomControlView.snp.top)
        }
        
        bottomControlView.snp.updateConstraints {[weak self] (make) in
            make.bottom.left.right.equalTo(self!.view)
            make.height.equalTo(48)
        }
        
        previewBtn.snp.updateConstraints {[weak self] (make) in
            make.centerY.equalTo(self!.bottomControlView)
            make.left.equalTo(self!.bottomControlView.snp.left).offset(10)
            make.height.equalTo(40)
            make.width.equalTo(60)
        }
        
        sendBtn.snp.updateConstraints {[weak self] (make) in
            make.centerY.equalTo(self!.bottomControlView)
            make.right.equalTo(self!.bottomControlView).offset(-10)
            make.height.equalTo(40)
        }
        
        selectCountLabel.snp.updateConstraints { [weak self](make) in
            make.centerY.equalTo(self!.bottomControlView)
            make.right.equalTo(self!.sendBtn.snp.left).offset(-3)
            make.height.width.equalTo(30)
        }
        
        if !hasScrollToBottom{
            
            assetCollectionView.scrollToItem(at: NSIndexPath(row: currentModel.assetResult!.count - 1, section: 0) as IndexPath, at: .bottom, animated: false)
        }
        
    }
    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

import Photos

class YDPhotoShowAlbumVCModel: MVVM_BaseVCModel ,UICollectionViewDataSource, UICollectionViewDelegate{
    
    override func onTapNavRightBtn() {
        self.MVVM_modelController?.dismiss(animated: true, completion: nil)
    }
    
    var parentVCModel:YDPhotoVCModel?{
        get{
            return parentViewModel as? YDPhotoVCModel
        }
    }
    
    var selectType:Int {
        get{
            if let x = parentVCModel{
                return x.selectType == 0 ? x.maxSelectNum : 1
            }else{
               return 9
            }
        }
    }
    
    var assetResult:PHFetchResult<AnyObject>?
    let imageCacher:PHCachingImageManager = PHCachingImageManager()
    
    let assetColloctionID = "assetColloctionID"
    
    
    init(assetResult:PHFetchResult<AnyObject>, parentVCModel:MVVM_BaseViewModel?) {
        self.assetResult = assetResult
        
        super.init(parentViewModel: parentVCModel)
        
    }
    
    
    override func viewController(vcIndex: Int) -> MVVM_BaseViewController? {
        return YDPhotoShowAlbumViewController()
    }
    
    //MARK: calc item size
    var columCount:CGFloat = 4
    var itemSpacing:CGFloat = 5
    let screenSize = UIScreen.main.bounds.size
    
    var itemSize:CGSize{
        get {
            let itemWidth = (screenSize.width - (columCount + 1) * itemSpacing) / columCount
            return CGSize(width: itemWidth, height: itemWidth)
        }
    }
    
    
    func setupCollectionLayout(layout:UICollectionViewFlowLayout){
        layout.itemSize = itemSize
        layout.minimumInteritemSpacing = itemSpacing
        layout.minimumLineSpacing = itemSpacing
        layout.sectionInset = UIEdgeInsets(top: itemSpacing, left: itemSpacing, bottom: itemSpacing, right: itemSpacing)
    }
    
    //MARK: -- dataSource
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return assetResult?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: assetColloctionID, for: indexPath) as! AssetCollectionViewCell
        if cell.viewModel.value == nil {
            let cellViewModel = AssetCollectionCellViewModel(photoAsset: assetResult?.object(at: indexPath.row) as? PHAsset , cacher: imageCacher, parentViewModel: self)
            cell.viewModel.value = cellViewModel
        }else if let x = cell.viewModel.value as? AssetCollectionCellViewModel{
            x.photoAsset.value = assetResult?.object(at: indexPath.row) as? PHAsset
        }else{
           print("item's model is not a AssetCollectionCellViewModel!")
        }
    
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        if let asset = assetResult?.object(at: indexPath.row) as? PHAsset{
            if asset.mediaType == .image{
                self.MVVM_navigationController?.pushVcModel(vcModel: YDPhotoPageVCModel.init(asserts: assetResult, startIndex: indexPath.row, parentVCModel: self))
            }else{
                if parentVCModel?.selectType == 0 {
                    YD_HUDCenter.share.svpHud.showMessage(message:"选图模式中无法选择视频" )
                    
                }else if parentVCModel?.selectType == 1{
                    MVVM_navigationController?.pushVcModel(vcModel: YDVideoPreviewVCModel.init(videoAsset: asset, parentViewModel: self))
                }
            }
        }
    }
    
    //MARK: -- selectImage Property
    let selectedAssets = Variable<[PHAsset]>([PHAsset]())
    let isUseOrignalData = Variable<Bool>(false)
    var pressImageToWidth = 500
    
    var maxSelectNum = 4
    
    func modifySelectedAssets(with asset:PHAsset){
        if maxSelectNum == 1{
            if selectedAssets.value.count == 0 {
                selectedAssets.value.append(asset)
            }else if selectedAssets.value.count == 1{
                selectedAssets.value[0] = asset
            }
        }else{
            if let index = selectedAssets.value.index(of: asset) {
                selectedAssets.value.remove(at: index)
            }else{
                
                if selectedAssets.value.count < maxSelectNum {
                    selectedAssets.value.append(asset)
                }else{
                    YD_HUDCenter.share.svpHud.showMessage(message: "最多能选择\(maxSelectNum)张图片！")
                }
            }
        }
    }
    
    //MARK:interaction
    func preview(){
        self.MVVM_navigationController?.pushVcModel(vcModel: YDPhotoPageVCModel.init(assertArr: selectedAssets.value, startIndex: 0, parentVCModel:  self))
    }
    
    func sendAction() {
        
        func getImages(with assets:[PHAsset]) -> [UIImage]{
           var result = [UIImage]()
            let option = PHImageRequestOptions()
            option.isSynchronous = true
            option.isNetworkAccessAllowed = true
            option.resizeMode = .exact
            option.deliveryMode = .highQualityFormat
            var pressImageSize:CGSize?
            for aAsset in selectedAssets.value {
                
                if isUseOrignalData.value {
                    pressImageSize = PHImageManagerMaximumSize
                }else{
                    let imageScaleFactor:CGFloat = CGFloat(pressImageToWidth) / CGFloat(aAsset.pixelWidth)
                    pressImageSize = CGSize(width: CGFloat(aAsset.pixelWidth) * imageScaleFactor, height: CGFloat(aAsset.pixelHeight) * imageScaleFactor)
                    
                }
                
                imageCacher.requestImage(for: aAsset, targetSize: pressImageSize!, contentMode: .aspectFill, options: option, resultHandler: { (x:UIImage?, _) in
                    if let realImage = x{
                        result.append(realImage)
                    }else{
                        print("get a image from asset failed!")
                    }
                })
            }
            return result
        }
        
       //sendAction
        
        parentVCModel?.assetsCallback?(selectedAssets.value)
        
        if let callback = parentVCModel?.imagesCallback {
            
            if let cropIamge = parentVCModel?.cropImageDelegate, self.selectedAssets.value.count == 1{
                
                self.MVVM_modelController?.dismiss(animated: false, completion:
                    {[weak self] in
                        cropIamge.cropImage(image: getImages(with: self!.selectedAssets.value)[0])
                    })
                return
                
            }
            
            callback(getImages(with: selectedAssets.value))
        }
        
        self.MVVM_modelController?.dismiss(animated: true, completion: nil)
    }
    
}

